import { useQuasar } from '@teld/q-components';
import Component from '@teld/q-components/Input';
import useMappingProps from 't/common/hooks/useMappingProps';
import {
  commonProps,
  fixNameSpace,
  pickOwnForBasicComponent,
} from 't/common/utils';
import { computed, defineComponent, ref, watch } from 'vue';
import Icon from '../icon';
import styles from '../input/index.module.scss';
import '../input/index.scss';
import LabelPrefixWraper from '../label-prefix-wraper';
import selfStyles from './index.module.scss';
import './index.scss';
import { isNaN, isNumber } from 'lodash';

export default defineComponent({
  name: fixNameSpace('QInputNumber'),
  props: {
    ...commonProps,
    ...Component.props,
    ...LabelPrefixWraper.props,
    prependIcon: {
      type: String,
    },
    appendIcon: {
      type: String,
    },
    label: {
      type: String,
      default() {
        return '';
      },
    },
    placeholder: {
      type: String,
      default() {
        return '';
      },
    },
    borderless: {
      type: Boolean,
      default() {
        return undefined;
      },
    },
    outlined: {
      type: Boolean,
      default() {
        return undefined;
      },
    },
    filled: {
      type: Boolean,
      default() {
        return undefined;
      },
    },
    maxLength: {
      type: Number,
    },
    borderType: {
      type: String,
      default() {
        return '';
      },
    },
    maxHeight: String,
    maxWidth: String,
    min: {
      type: [String, Number],
      default() {
        return 0;
      },
    },
    max: {
      type: [String, Number],
    },
    step: {
      type: [String, Number],
    },
    accuracy: {
      type: Number,
      default() {
        return 0;
      },
    },
  },
  emits: ['focus','blur', 'change'],

  setup(props, { attrs, emit, expose, slots }) {
    const $q = useQuasar();
    const refComponent = ref();
    const [mappingProps, mappingExpose] = useMappingProps(props, {
      clear() {
        refComponent.value.clear(...arguments);
      },
      update() {
        refComponent.value.update(...arguments);
      },
      focus() {
        refComponent.value.focus(...arguments);
      },
      blur() {
        refComponent.value.blur(...arguments);
      },
      validate() {
        return refComponent.value.validate(...arguments);
      },
      resetValidation() {
        refComponent.value.resetValidation(...arguments);
      },
    });
    expose(mappingExpose);
    mappingProps.modelValue = isNumber(mappingProps.modelValue)
      ? mappingProps.modelValue?.toFixed(mappingProps.accuracy ?? 0)*1
      : !isNaN(parseFloat(mappingProps.modelValue))? parseFloat(mappingProps.modelValue) : '';
    checkNum();
    emit(
      'update:modelValue',
      mappingProps.modelValue,
    );

    let isMobile = computed(() => {
      // return $q.screen.xs;
      return $q.platform.is.mobile;
    });
    watch(
      () => mappingProps.modelValue,
      (newValue, oldValue) => {
        if (
          (newValue === '' || newValue === null) &&
          (oldValue === '' || oldValue === null)
        ) {
          return; // 如果 newValue 和 oldValue 都为空字符串或 null，则直接返回不执行后续逻辑
        }
        if (newValue?.toString() != oldValue?.toString()) {
          checkNum();
          // mappingProps.modelValue = mappingProps.modelValue?.toString()
          //   ? typeof mappingProps.modelValue === Number
          //     ? mappingProps.modelValue?.toFixed(mappingProps.accuracy ?? 0) * 1
          //     : Number(mappingProps.modelValue)?.toFixed(
          //         mappingProps.accuracy ?? 0,
          //       ) * 1
          //   : '';
          emit('update:modelValue', mappingProps.modelValue);
          emit(
            'change',
             mappingProps.modelValue,
          );

        }
      },
    );
    function checkNum() {
      if (
        isNumber(mappingProps.modelValue) ||
        !isNaN(parseFloat(mappingProps.modelValue))
      ) {
        const num = parseFloat(mappingProps.modelValue);
        const max =
          !mappingProps.max && mappingProps.max !== 0
            ? ''
            : parseFloat(mappingProps.max);
        const min =
          !mappingProps.min && mappingProps.min !== 0
            ? ''
            : parseFloat(mappingProps.min);

        if (Number.isNaN(num) || (min !== '' && max !== '' && min > max)) {
          return;
        }
        let updatedNum = num;
        if (max !== '') {
          updatedNum = Math.min(updatedNum, max);
        }
        if (min !== '') {
          updatedNum = Math.max(updatedNum, min);
        }
        console.log(updatedNum);
        const fixedNum = updatedNum.toFixed(mappingProps.accuracy ?? 0)*1;
        mappingProps.modelValue = fixedNum;
        // emit('update:modelValue', fixedNum);
      } else {
        mappingProps.modelValue = '';
      }
    }

    function decrease() {
      let num =
        typeof mappingProps.modelValue === Number
          ? mappingProps.modelValue
          : Number(mappingProps.modelValue);
      if (num > mappingProps.min || !mappingProps.min) {
        mappingProps.modelValue = (num - (mappingProps.step ?? 1)).toFixed(
          mappingProps.accuracy ?? 0,
        )*1;
        // emit(
        //   'update:modelValue',
        //   (num - (mappingProps.step ?? 1)).toFixed(mappingProps.accuracy ?? 0),
        // );
      }
    }
    function increase() {
      console.log('increase');
      let num =
        typeof mappingProps.modelValue === Number
          ? mappingProps.modelValue
          : Number(mappingProps.modelValue);
      if (num < mappingProps.max || !mappingProps.max) {
        mappingProps.modelValue = (num + (mappingProps.step ?? 1)).toFixed(
          mappingProps.accuracy ?? 0,
        )*1;
        // emit(
        //   'update:modelValue',
        //   (num + (mappingProps.step ?? 1)).toFixed(mappingProps.accuracy ?? 0),
        // );
      }
    }
    return () => {
      let Type = mappingProps.borderType
        ? Object.fromEntries(
            ['outlined', 'standout', 'filled', 'borderless'].map(k => {
              return [k, mappingProps[k] ?? mappingProps.borderType === k];
            }),
          )
        : {};

      if (isMobile.value) {
        mappingProps.clearable = false;
      }
      //  console.log(Type,'Type')

      //=============去除内部hover时虚线边框========
      let attrs_ = { ...attrs };
      delete attrs_['data-uid'];
      delete attrs_['data-tag'];

      return (
        <div
          class={[
            'tr-input-default',
            mappingProps.labelPosition == 'top' && 'tr-input-default-top',
            (mappingProps.requiredMessage || mappingProps.maxLength) &&
              'tr-input-requiredmessage',
            mappingProps.borderType == 'standout' && 't-input-standard',
            'tr-input-form',
            mappingProps.readonly && 'tr-input-readonly',
            (mappingProps.disable || mappingProps.disabled) &&
              'tr-input-disabled',
          ]}
          v-show={mappingProps.visible}
          {...attrs}
          tabindex={-1}
        >
          <LabelPrefixWraper
            required={mappingProps.required}
            label={mappingProps.label}
            labelProps={{ class: 'input-title' }}
            hideLabel={mappingProps.hideLabel}
            readonly={mappingProps.readonly}
            labelPosition={mappingProps.labelPosition}
            helpConf={mappingProps.helpConf}
            helpTooltip={mappingProps.helpTooltip}
            helpPlacement={mappingProps.helpPlacement}
            helpMore={mappingProps.helpMore}
            maxHeight={mappingProps.maxHeight}
            maxWidth={mappingProps.maxWidth}
            helpMorePopup={mappingProps.helpMorePopup}
            helpMoreLink={mappingProps.helpMoreLink}
            helpMoreLinkHrefStatic={mappingProps.helpMoreLinkHrefStatic}
            helpMoreLinkHrefExp={mappingProps.helpMoreLinkHrefExp}
          ></LabelPrefixWraper>
          <Component
            ref={refComponent}
            class={[
              't-input',
              'tr-input-number',
              styles.module,
              selfStyles.module,
              !mappingProps.readonly && !mappingProps.disable
                ? 'q-placeholder-text-right'
                : '',
            ]}
            {...attrs_}
            {...pickOwnForBasicComponent(mappingProps, Component.props, attrs_)}
            label={undefined}
            {...Type}
            placeholder={mappingProps.placeholder || attrs.placeholder}
            type='number'
            title=''
            step={mappingProps.step}
            min={mappingProps.min}
            max={mappingProps.max}
            onFocus={e => {
              refComponent.value.select();
              emit('focus', e);
            }}
            onBlur={e => {
              emit('blur');
            }}
            borderless
            // style='text-align:right;'
            tabindex={mappingProps.tabIndex ? mappingProps.tabIndex : 1}
            debounce={300}
            reactive-rules
          >
            {{
              prepend: isMobile.value ? undefined : slots.prepend?.(),
              append: isMobile.value ? undefined : (
                <div
                  style='display:flex;flex-direction: column;height: inherit;justify-content: space-evenly;'
                  v-show={!mappingProps.readonly && !mappingProps.disable}
                >
                  <Icon
                    name='icon-t-caret-up-outlined'
                    class='cursor-pointer divarrow'
                    size='8px'
                    onClick={increase}
                    color='rgba(0, 0, 0, 0.4)'
                  />
                  <Icon
                    name='icon-t-caret-down-outlined '
                    class='cursor-pointer divarrow'
                    size='8px'
                    onClick={decrease}
                    color='rgba(0, 0, 0, 0.4)'
                  />
                </div>
              ),
            }}
          </Component>
        </div>
      );
    };
  },
});
